package com.xxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.dto.UserDto;
import com.xxx.pojo.*;
import com.xxx.service.CommentService;
import com.xxx.service.FileService;
import com.xxx.service.RequestInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private RequestInfoService requestInfoService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private FileService fileService;

    @Value("${image.path}")
    private String imagePath;

    @Transactional
    @RequestMapping("/save")
    public Result save(@RequestBody Comment comment) {
        log.info("comment:{}", comment);
        comment.setCreateTime(LocalDateTime.now());
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RequestInfo one = null;
        if (principal == null) {
            one = requestInfoService.getOne(new LambdaQueryWrapper<RequestInfo>()
                    .eq(RequestInfo::getEmail, comment.getEmail()));
            if (one != null) {
                boolean save = commentService.save(comment);
                return save ? Result.success("保存成功") : Result.error("系统内部错误");
            }
            return Result.error(600, "邮箱不存在");
        }

        boolean save = commentService.save(comment);
        return save ? Result.success("保存成功") : Result.error("系统内部错误");
    }


    @PreAuthorize("hasAnyAuthority('sys:select:comment')")
    @Transactional
    @PostMapping("/select")
    public Result selectUserByCondition(@RequestBody Comment comment, @RequestParam("current") Integer current, @RequestParam("size") Integer size){
        if (Objects.isNull(comment)){
            throw new RuntimeException("数据传输格式错误!~");
        }
        if (comment.getStatus() == null || comment.getStatus().getI() == 2){
            comment.setStatus(null);
        }
        IPage iPage = new Page(current,size);
        IPage page = commentService.page(iPage,new LambdaQueryWrapper<Comment>().eq(comment.getStatus() != null,Comment::getStatus,comment.getStatus())
                .eq(comment.getId() != null && comment.getId()>0,Comment::getId,comment.getId()).like(comment.getName() != null && comment.getName() != "",Comment::getName,comment.getName())
                .eq(Comment::getDeleted,0));
        List<Comment> comments = page.getRecords();

        HashMap<String, Object> map = new HashMap<>();
        map.put("list",comments);
        map.put("total", page.getTotal());
        return Result.success("",map);
    }

    @PreAuthorize("hasAnyAuthority('sys:update:comment')")
    @Transactional
    @PutMapping("/update")
    public Result updateComment(@RequestBody Comment comment){
        if (Objects.isNull(comment)){
            throw new RuntimeException("数据传输格式错误!~");
        }
        boolean b = commentService.updateById(comment);
        if (!b){
            return Result.error("修改失败!");
        }
        return Result.success("修改成功!");
    }


    @PreAuthorize("hasAnyAuthority('sys:delete:comment')")
    @Transactional
    @DeleteMapping("/delete/{ids}")
    public Result deleteCommentByIds(@PathVariable("ids") List<Long> ids){
        boolean b=true;
        for (Long id : ids) {
            commentService.update(new LambdaUpdateWrapper<Comment>().set(Comment::getImg,"").eq(Comment::getId,id));
            Comment comment = commentService.getById(id);
            fileService.delImage(comment.getImg());
            b = commentService.removeById(id);

        }
        if (!b){
            return Result.error("删除失败!");
        }
        return Result.success("删除成功!");
    }


    @GetMapping("/time")
    public Result selectCommentByTime(){
        List<Comment> list = commentService.list(new LambdaQueryWrapper<Comment>().orderByDesc(Comment::getCreateTime).last("LIMIT 4"));
        return (list == null) ? Result.error("查询错误") : Result.success("查询成功",list);
    }
}
